{-  Copyright (C) 2014 Mark W Pearse  
  This program is free software: you can redistribute it and/or modify
  it under the terms of the GNU General Public License as published by
  the Free Software Foundation, either version 3 of the License, or
  (at your option) any later version.

-}

module Main where

import E_Data
import E_rawAPI (usleep)
import E_API
import EpuAlloc
import EpuCode
import Text.Printf

epuSrc = "int_types_e"
_BufOffset = 0x01000000
_BufSize = 4096
baseAddr = EpuAddr 0x2000

main = do
-- prepare data that will be used on each Epiphany core
    let defs = [EpuDef "_BufOffset" _BufOffset, EpuDef "_BufSize" _BufSize]
    let oneInt = [0::Int]
    let ebs = [(EpuBlock "pRow" oneInt), (EpuBlock "pCol" oneInt)]
    let epudata = allocate baseAddr ebs
    putStrLn $ show epudata
    let refRow = findBlock epudata "pRow"
    let refCol = findBlock epudata "pCol"

-- compile c program for each core using these allocations
    maybeCPM <- compileForEpu defs epudata epuSrc
    case maybeCPM of
        Nothing -> return ()
        Just coreProgM -> do
            withEpiphanyInfo (\pInfo -> do
                let oneCore = GrpSize 1 1
                let fullSize = platformSize pInfo
                let origin = (EpuPos 0 0)
                putStrLn "Interrupt test"
                withGroup origin fullSize (flip (epuLoadProg coreProgM) fullSize)-- load program on all cores
                withBuffer _BufOffset _BufSize (\memptr -> do	-- Allocate the ext. mem. mailbox
                    let doOneCore pos @ (EpuPos row col)= do
                        withGroup pos oneCore (\coreref -> do
                            writeEpuBlock coreref origin (refRow {eaVal = [row]})
                            writeEpuBlock coreref origin (refCol {eaVal = [col]})
			    printf "Message from eCore (%1d, %1d): \n" row col
			    epuStartGroup coreref
			    usleep(20000);
			    result <- ememReadString memptr 0 _BufSize
			    putStrLn result)
                        in mapM_ doOneCore (allcores pInfo) ) )

